(function ($, window) {
    /**
     * 全局统计事件统一独立出来, 前端JS文件结构化处理
     * @processor randal
     * @createdAt 2020-09-02 14:20:02
     */

    /**
     * 初始化统计, 页面加载完自动执行统计操作
     */
    $(function () {
        var renderingEndTime = (new Date()).valueOf();
        var referrer = $('#referrer').val();
        var currentUrl = $('#currentUrlInput').val();
        var runtimeCounting = (renderingEndTime - renderingStartTime) / 1000;
        var exectime = Param.execTime;
        var uid = Param.uid;
        var uv = Param.uv_id;
        var user_created_at = Param.user_created_at;

        /**
         * 页面统计
         */
        $.ajax({
            type: "post",
            url: Url.basicsStatistics,
            data: {
                type: Param.pageCodeId || 0,
                url: referrer,
                exectime: Param.execTime,
                run_time: runtimeCounting,
                currentUrl: currentUrl,
                pageType: Param.pageType,
                userIP: Param.userIP,
                '_csrf-frontend': $('meta[name="csrf-token"]').attr('content'),
                "platform_id": "1",
                "create_time": Param.timestamp,
                "redis_id": 0,
                "uid": Param.uid,
                "user_created_at": user_created_at,
                "vip": Param.is_vip,
                "before_url": document.referrer,
                "referrer": Param.channel_referrer,
                "from": Param.channel_from,
                "keyword": Param.channel_keyword,
                "page_code": Param.buryingPointPageCode,
                "page_type": Param.buryingPointPageType,
                "session_id": Param.sid,
                "ua": navigator.userAgent,
                "class_id": Param.class_id,
                "content_tag_id": Param.content_tag_id,
            },
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            success: function (message) {
            }
        });

        var spm = Param.spm_referrer;
        var spmArr = [];
        if(spm !=''){
            spmArr = spm.split('.');
        }

        window.pageUpload({
            uid : uid,
            uv: uv,
            referrer:referrer,
            runtimeCounting:runtimeCounting,
            currentUrl:currentUrl,
            exectime:exectime,
            spmArr:spmArr,
            url_route: Url.spmprefix,
            user_created_at:user_created_at,
        });

        window.hukeStatistics.statisticsPageVisit({
            'uv': uv,
            'exectime': Math.round(exectime * 1000) / 1000,
            'runtime': runtimeCounting,
            'current_url': currentUrl,
            'vip': formatInt(Param.is_vip),
            'before_url': document.referrer,
            'referrer': Param.channel_referrer,
            'from': Param.channel_from,
            'keyword': Param.channel_keyword,
            'page_code': formatInt(Param.buryingPointPageCode),
            'page_type': formatInt(Param.buryingPointPageType),
            'session_id': Param.sid,
            'unique_page_id': Param.unique_id,
            'ua': navigator.userAgent,
            'regd': formatInt(Param.regd),
            'uuid': Param.uuid,
            'url_route':  Url.spmprefix,
            'route': spmArr ? spmArr[0] : '',
            'module': spmArr ? formatInt(spmArr[1]) : 0,
            'position': spmArr ? formatInt(spmArr[2]) : 0,
            "user_created_at": user_created_at,
        });
    });

    window.pageUpload = function (obj) {
        var logHost = 'cn-shanghai.log.aliyuncs.com';
        var logProject = 'huke';
        var logStore = 'web_log';
        var logger = new window.Tracker(logHost, logProject, logStore);
        var spmArr = obj.spmArr;


        logger.push('uid', formatInt(obj.uid));
        logger.push('uv', obj.uv);
        logger.push('user_created_at', obj.user_created_at);
        logger.push('referrerUrl', obj.referrer);
        logger.push('exectime', Math.round(obj.exectime * 1000) / 1000);
        logger.push('runtime', obj.runtimeCounting);
        logger.push('currentUrl', obj.currentUrl);
        logger.push('vip', formatInt(Param.is_vip));
        logger.push('before_url', document.referrer);
        logger.push('referrer', Param.channel_referrer);
        logger.push('from', Param.channel_from);
        logger.push('keyword', Param.channel_keyword);
        logger.push('page_code', formatInt(Param.buryingPointPageCode));
        logger.push('page_type', formatInt(Param.buryingPointPageType));
        logger.push('session_id', Param.sid);
        logger.push('ua', navigator.userAgent);
        logger.push('regd', formatInt(Param.regd));
        logger.push('uuid', Param.uuid);
        logger.push('unique_id', Param.unique_id);
        logger.push('url_route', obj.url_route);
        logger.push('route', spmArr ? spmArr[0] : '');
        logger.push('module', spmArr ? formatInt(spmArr[1]) : 0);
        logger.push('position', spmArr ? formatInt(spmArr[2]) : 0);
        logger.push('date', getDate() );
        logger.push('screen_height', screen.height);
        logger.push('screen_width', screen.width);
        if (typeof webLogExtendData !== 'undefined') {
            logger.push('expand_json_data', JSON.stringify(webLogExtendData));
        }
        logger.logger();
    }

    /**
     * 点击上报日志
     * @param obj
     */
    var clickUpload = function (obj) {
        var logHost = 'cn-shanghai.log.aliyuncs.com';
        var logProject = 'huke';
        var logStore = 'user_aciton_statistics';
        var logger = new window.Tracker(logHost, logProject, logStore);
        logger.push('uv', obj.uv);
        logger.push('page', obj.page);
        logger.push('ip', obj.ip);
        logger.push('element', obj.element);
        logger.push('client_type', obj.clientType);
        logger.push('event_type', obj.eventType);
        logger.push('event_id', obj.eventId);
        logger.push('user_agent', obj.userAgent);
        logger.push('user_attr', obj.userAttr);
        logger.push('user_type', obj.userType);
        logger.push('user_custom', obj.custom);
        logger.push('user_uid', formatInt(obj.uid));
        logger.push('video_class_id', obj.videoClassId || 0);
        logger.push('user_created_at', obj.user_created_at);
        logger.logger();
    };

    /**
     * 获取请求地址，或者参数
     * @param type 1:获取访问地址,2:获取访问地址携带的参数
     * @returns {string}
     */
    var getUrlInfo = function (type) {
        var url = document.location.toString();
        var arrUrl = url.split("?");
        if (type === 1) {
            return arrUrl[0];
        }

        var search = location.search; //获取url中"?"符后的字串
        var theRequest = {};
        if (search.indexOf("?") !== -1) {
            var str = search.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        }
        return JSON.stringify(theRequest);
    };

    // JQuery Document element.
    var $document = $(window.document)

    /**
     * 需要统计的元素绑定点击事件
     * @author D
     * @original public.final.js
     */
    $document.on('click', '[user_action_type="statistics"]', function () {
        var element = $(this).attr('user_action_explain');
        var elementId = $(this).attr('user_action_id');
        var custom;
        //额外唯一性参数判断json对象
        if ($(this).attr('user_action_custom')) {
            if (Param.uid * 1 > 0) {
                custom = {
                    unique: Param.uid + '-' + $(this).attr('user_action_custom'),
                }
            } else { //未登陆，使用uv
                custom = {
                    unique: Param.uv_id + '-' + $(this).attr('user_action_custom'),
                }
            }
        } else {
            //针对需要统计单个用户的情况，未登陆用uv判断一个用户唯一性，如果登陆使用uid判断用户唯一性
            if (Param.uid * 1 > 0) {
                custom = {
                    unique: Param.uid,
                }
            } else { //未登陆，使用uv
                custom = {
                    unique: Param.uv_id,
                }
            }
        }
        custom = JSON.stringify(custom)
        var userAgent = navigator.userAgent;
        var data = {
            'uv': Param.uv_id,
            'page': getUrlInfo(1),
            'ip': Param.decUserIP,
            'element': element,
            'clientType': 1,
            'eventType': 1,
            'eventId': elementId,
            'userAgent': userAgent,
            "userType": Param.userLoginType,
            'userAttr': getUrlInfo(2),
            'custom': custom,
            'uid': formatInt(Param.uid),
            'videoClassId': Param.class_id || 0,
            'user_created_at':Param.user_created_at,
        };
        clickUpload(data);
    });

    /**
     * 元素绑定点击统计事件, 作用同上, 属性名`data`化
     * @author randal
     * @usage element with attribute:
     *      - data-action="statistics" 标准化标识名
     *      - data-statistics-id="ELEMENT_ID" 按钮ID
     *      - data-statistics-description="ELEMENT_DESCRIPTION" 按钮说明
     */
    $document.on('click', '.btn-statistics,[data-action=btn-statistics]', function () {
        var customData = $(this).data('statisticsCustom')
            , id = $(this).data('btnId') || 0
            , desc = $(this).data('btnDesc') || ''
            , type = $(this).data('btnType') || 0
            , ua = window.navigator.userAgent
            , videoClassId = Param.class_id || 0;
        if (!id) {
            return;
        }
        var LOG_HOST = 'cn-shanghai.log.aliyuncs.com';
        var LOG_PROJECT = 'huke';
        var LOG_STORE = 'web-btn-click-statistics';
        $.get(generateAliLogTrackUrl(LOG_HOST, LOG_PROJECT, LOG_STORE), {
            'uv': Param.uv_id,
            'ip': Param.decUserIP,
            'client_type': 1,
            'uid': formatInt(Param.uid),
            'btn_type': type,
            'btn_id': id,
            'btn_desc': desc,
            'user_agent': ua,
            'user_type': Param.userLoginType,
            'url_page': getUrlInfo(1),
            'url_attr': getUrlInfo(2),
            'video_class_id': videoClassId
        })
    });

    /**
     * 视频列表标签点击统计
     */
    $document.on('click', '[data-action=tags-watcher]', function () {
        var target = $(this).data('watcherType');
        var id = $(this).data('tagId');
        var name = $(this).data('tagName');
        id && window.videoTagsBehaviorsWatcher(id, name, target, 'tag-click');
    });

    function generateAliLogTrackUrl(host, project, store) {
        return '//' + project + '.' + host + '/logstores/' + store + '/track?APIVersion=0.6.0';
    }

    /**
     * 视频标签点击行为监控统计
     * @param {string} id 标签ID
     * @param {string} name 标签名称
     * @param {string} type 标签类型
     * @param {string} action 标签动作
     * @param {object} [ext] 额外数据 值必须是字符型
     * @return {void}
     * @global 注册到全局函数
     */
    window.videoTagsBehaviorsWatcher = function (id, name, type, action, ext) {
        var LOG_HOST = 'cn-shanghai.log.aliyuncs.com';
        var LOG_PROJECT = 'huke';
        var LOG_STORE = 'web-tags-behaviors-watcher';
        var logs = [];
        if (typeof id === 'string' && id.indexOf(',') !== -1) {
            id = id.split(',').filter(function (v) {
                return !!(v - 0);
            });
        }
        if (id instanceof Array) {
            $.each(id, function (_, tagId) {
                logs.push($.extend({}, ext, {tag_id: '' + tagId, tag_type: type, action: action, uuid: window.Param.uuid}));
            });
        } else {
            logs.push($.extend({}, ext, {tag_id: '' + id, tag_name: name, tag_type: type, action: action, uuid: window.Param.uuid}));
        }
        if (logs.length === 0) {
            return;
        }
        batchPutLogs(generateAliLogTrackUrl(LOG_HOST, LOG_PROJECT, LOG_STORE), logs);
    };

    $document.on('click', function (e) {
        var REPORT_MODULE_CLASS = '.report-module';
        if($(e.target).parents(REPORT_MODULE_CLASS).length > 0) {
            if($(e.target).closest('[report-position-id]').length > 0 && $(e.target).closest('a').length <= 0){
                //非a标签并且含有report-position-id属性
                var link = $(e.target).closest('[report-position-id]'),
                    trail = $(e.target).parents(REPORT_MODULE_CLASS),
                    id = trail.attr('report-module-id'),
                    aid = link.attr('report-position-id');
                window.spmClickData(id, aid);
            } else if($(e.target).closest('a').length > 0){
                //是a标签
                var link = $(e.target).closest('a'),
                    href = link.attr('href'),
                    trail = $(e.target).parents(REPORT_MODULE_CLASS),
                    id = trail.attr('report-module-id'),
                    i = trail.find('a').not('report-position-id').index(link) + 1,
                    aid = link.attr('report-position-id') ? link.attr('report-position-id') : i;

                if (href &&  href.indexOf('javascript') === -1 && href.indexOf('spm_from_id') === -1) {//如果链接添加过标识，不重新添加
                    if (href.indexOf('?') != -1) {
                        link.attr('href', href + '&spm_from_id=' + Url.spmprefix + '.' + id + '.' + aid);
                    } else {
                        link.attr('href', href + '?spm_from_id=' + Url.spmprefix + '.' + id + '.' + aid);
                    }
                }
                window.spmClickData(id, aid);
            }
        }
    });

    window.spmClickData = function (module, position) {

        //点击事件上报
        window.hukeStatistics.statisticsClickEvent({
            'from': Param.channel_from,
            'keyword': Param.channel_keyword,
            'module': formatInt(module),
            'position': formatInt(position),
            'regd': formatInt(Param.regd),
            'route': Url.spmprefix,
            'uuid': Param.uuid,
            'uv': Param.uv_id,
            'session_id': Param.sid,
            'unique_page_id': Param.unique_id,
            'vip': formatInt(Param.is_vip),
            'click_envent_play_video_class':Param.video_id ? formatInt(Param.video_id) : 0,
            'user_created_at':Param.user_created_at,
        });

        var logHost = 'cn-shanghai.log.aliyuncs.com';
        var logProject = 'huke';
        var logStore = 'web_click_log';
        var logger = new window.Tracker(logHost, logProject, logStore);
        logger.push('created_at', Param.timestamp);
        logger.push('from', Param.channel_from);
        logger.push('ip', Param.decUserIP);
        logger.push('keyword', Param.channel_keyword);
        logger.push('module', formatInt(module));
        logger.push('position', formatInt(position));
        logger.push('referrer', Param.channel_referrer);
        logger.push('regd', formatInt(Param.regd));
        logger.push('route', Url.spmprefix);
        logger.push('uid', formatInt(Param.uid));
        logger.push('uuid', Param.uuid);
        logger.push('uv', Param.uv_id);
        logger.push('session_id', Param.sid);
        logger.push('vip', formatInt(Param.is_vip));
        logger.push('date', getDate() );
        logger.push('unique_id', Param.unique_id);
        logger.push('click_envent_play_video_class', Param.video_id ? formatInt(Param.video_id) : 0);
        logger.push('user_created_at', Param.user_created_at);
        logger.logger();
    };

    // 监听弹窗显示统计
    window.watchPopupShow = function (popupId,extendVal) {
        var extendVal = arguments[1] ? arguments[1] : '';

        var logHost = 'cn-shanghai.log.aliyuncs.com';
        var logProject = 'huke';
        var logStore = 'popup_log';
        var logger = new window.Tracker(logHost, logProject, logStore);

        function getQuery(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return '';
        }

        logger.push('ip', Param.decUserIP);
        logger.push('page', Param.currentUrl);
        logger.push('route', Url.spmprefix);
        logger.push('popup_id', popupId);
        logger.push('extend_val', extendVal);
        logger.push('uid', Param.uid);
        logger.push('login_type', Param.userLoginType);
        logger.push('vip_type', Param.UserVipIdentifyNum);
        logger.push('regd', Param.regd);
        logger.push('spm_from_id', getQuery('spm_from_id'));
        logger.push('client_id', '0');
        logger.push('ua', navigator.userAgent);
        logger.push('uv', Param.uv_id);
        logger.push('unique_id', Param.unique_id);
        logger.push('uuid', Param.uuid);
        logger.push('session_id', Param.sid);
        logger.push('channel_referrer', Param.channel_referrer);
        logger.push('channel_from', Param.channel_from);
        logger.push('channel_keyword', Param.channel_keyword);


        logger.logger();
    };
    /**
     * 批量插入日志
     * @param {string} url 日志插入url
     * @param {Array|Object} logs 日志内容 日志数组或单条日志, 单条日志会被整合成数组执行批量插入
     * @param {string} [topic] 日志主题。
     * @param {string} [source] 日志来源。
     * @param {Object} [tags] 日志标签。
     * @return {void}
     */
    var batchPutLogs = function (url, logs, topic, source, tags) {
        if (!logs instanceof Array) {
            logs = [logs];
        } else if ([url, logs].indexOf(undefined) !== -1 || logs.length === 0) {
            return;
        }
        $.ajax({
            url: url,
            method: 'post',
            data: JSON.stringify({
                __topic__: topic,
                __source__: source,
                __logs__: logs,
                __tags__: tags
            }),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            headers: {
                "x-log-apiversion": "0.6.0",
                "x-log-bodyrawsize": "1234",
            }
        });
    };

    function formatInt(num) {
        return parseInt(num);
    }

    function getDate() {
        var currentDate = new Date();
        return currentDate.getFullYear() + '-' + appendzero((currentDate.getMonth() + 1)) + '-' + currentDate.getDate();
    }

    function appendzero (obj) {
        if (obj < 10) return "0" + obj; else return obj;
    }
})(jQuery, window);
